package cn.kshost.zqyg.user.service.impl;

import cn.kshost.zqyg.exception.ZhongQiaoException;
import cn.kshost.zqyg.model.dto.h5.UserLoginDto;
import cn.kshost.zqyg.model.dto.h5.UserRegisterDto;
import cn.kshost.zqyg.model.entity.user.UserInfo;
import cn.kshost.zqyg.model.vo.common.ResultCodeEnum;
import cn.kshost.zqyg.model.vo.h5.UserInfoVo;
import cn.kshost.zqyg.user.mapper.UserMapper;
import cn.kshost.zqyg.user.service.UserService;
import cn.kshost.zqyg.utils.AuthContextUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
     private UserMapper userMapper;
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String code = userRegisterDto.getCode();
        String nickName = userRegisterDto.getNickName();



        //判断数据是否异常
  if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(code) || StringUtils.isEmpty(nickName)) {
      throw new  ZhongQiaoException(ResultCodeEnum.DATA_ERROR);
  }
        //判断验证码是否异常
        String redisCode = redisTemplate.opsForValue().get("phone:code:" + userRegisterDto.getUsername());
        if(!code.equals(redisCode)){
            throw new  ZhongQiaoException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //判断用户名是否存在
        UserInfo userInfo =  userMapper.selectUserByUsername(username);
        if(null != userInfo){
            throw  new ZhongQiaoException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //保存用户信息
        userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setNickName(nickName);
        userInfo.setPhone(username);
        userInfo.setSex(0);
        userInfo.setStatus(1);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        //添加数据
        userMapper.insertUserInfo(userInfo);
        //删除redis数据
        redisTemplate.delete("phone:code:" + username);
    }

    @Override
    public String login(UserLoginDto userLoginDto,String ip) {
        String username =   userLoginDto.getUsername();
        String password =   userLoginDto.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        //判断用户名密码是否合规
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new  ZhongQiaoException(ResultCodeEnum.DATA_ERROR);
        }
        //判断用户是否存在
        UserInfo userInfo = userMapper.selectUserByUsername(username);
        if (null == userInfo) {
            throw new  ZhongQiaoException(ResultCodeEnum.DATA_ERROR);
        }
        //判断密码是否匹配
        if (!md5Password.equals(userInfo.getPassword())) {
            throw new  ZhongQiaoException(ResultCodeEnum.LOGIN_ERROR);
        }
        //判断账号是否可用
        if (userInfo.getStatus() == 0){
            throw  new  ZhongQiaoException(ResultCodeEnum.ACCOUNT_STOP);
        }
        //更新用户信息
        userInfo.setLastLoginIp(ip);
        userInfo.setLastLoginTime(new Date());

        userMapper.updateById(userInfo);
        //生成token 存入redis
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:login:"+token, JSON.toJSONString(userInfo),30, TimeUnit.DAYS);
        //返回token
        return token;
    }

    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
//        String userInfoJson = redisTemplate.opsForValue().get("user:login:" + token);
//        if (StringUtils.isEmpty(userInfoJson)) {
//            throw  new ZhongQiaoException(ResultCodeEnum.LOGIN_AUTH);
//        }
//        UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
        //通过thereadlocal获取用户信息 而非redis
        UserInfo userInfo = AuthContextUtil.getUserInfoValue();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }
}
